package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.util.DateUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.mq.listener.vo.IotMsgNotifyData;
import com.zzyl.nursing.mq.listener.vo.IotMsgService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备数据Service业务层处理
 *
 * @author zs
 * @date 2025-10-14
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    /**
     * 查询设备数据
     *
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id) {
        return deviceDataMapper.selectById(id);
    }

    /**
     * 查询设备数据列表
     *
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData) {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData) {
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData) {
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除设备数据
     *
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids) {
        return deviceDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备数据信息
     *
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id) {
        return deviceDataMapper.deleteById(id);
    }


    /**
     * 存储设备数据
     *
     * @param iotMsgNotifyData
     */
    @Override
    @Transactional
    public void insertDeviceDataBatch(IotMsgNotifyData iotMsgNotifyData) {
        ArrayList<DeviceData> deviceDatas = new ArrayList<>();
        //先根据iotId查找设备表，设备存在就新增数据，不存在直接返回
        String iotId = iotMsgNotifyData.getHeader().getDeviceId();
        LambdaQueryWrapper<Device> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Device::getIotId, iotId);
        Device device = deviceMapper.selectOne(lqw);

        if(device==null){
            return;
        }

        List<IotMsgService> services = iotMsgNotifyData.getBody().getServices();
        for (IotMsgService service : services) {

            //处理上报时间日期
            LocalDateTime eventTime =  LocalDateTimeUtil.parse(service.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
            //日期时区转换
            LocalDateTime alarmTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();

            Map<String, Object> properties = service.getProperties();


            properties.forEach((key, value) -> {

                //将device赋值给deviceData
                DeviceData deviceData = BeanUtil.toBean(device, DeviceData.class);
                deviceData.setId(null);
                deviceData.setAccessLocation(device.getBindingLocation());
                deviceData.setFunctionId(key);
                deviceData.setDataValue(value.toString());
                deviceData.setAlarmTime(alarmTime);

                deviceDatas.add(deviceData);
            });
        }
        saveBatch(deviceDatas);

        //然后将设备数据存到redis中，方便后续查询
        redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA,iotId, JSONUtil.toJsonStr(deviceDatas));
    }

    /**
     * 定时删除设备数据
     */
    @Override
    public void periodicDeletionDeviceData() {
        //每天凌晨0点删除15天之前的数据
        LambdaQueryWrapper<DeviceData> lqw = new LambdaQueryWrapper<>();
        lqw.lt(DeviceData::getAlarmTime,LocalDateTime.now().minusDays(15));
        remove(lqw);
    }
}
